import { baseURL } from "../config.js";
/* 提示 */
export let Toast = (title, icon, time) => {
  uni.showToast({
    title,
    icon: icon || "none",
    mask: true,
    duration: time || 2000,
  });
};

/* 路由跳转 */
export function handleClickRouter(e) {
  let token = wx.getStorageSync("X-MINI-TOKEN");
  if (!token) {
    whetherLogin();
    return;
  }

  let url = e.currentTarget.dataset.url;
  let type = e.currentTarget.dataset.type;
  let firm = e.currentTarget.dataset.firm || false; //当下无企业  跳转到添加企业页面
  if (firm) {
    uni.navigateTo({
      url: "/selfInfo/myBusiness/addBusiness",
    });
    return false;
  }

  if (type == "tabBar") {
    uni.switchTab({
      url,
    });
  } else {
    uni.navigateTo({
      url,
    });
  }
}

// 判断当前用户是否登录
export const whetherLogin = () => {
  let token = uni.getStorageSync("X-MINI-TOKEN");
  if (!token) {
    uni.showModal({
      title: "提示",
      content: "请先登录",
      success: function (res) {
        if (res.confirm) {
          wx.redirectTo({
            url: "/pages/beforeLogin/beforeLogin",
          });
          return;
        } else if (res.cancel) {
          return false;
        }
      },
    });
  }
};
// 加载提示
export function isLoading(flag = true) {
  if (flag) {
    uni.showLoading({
      title: "加载中...",
      mask: true,
    });
  } else {
    uni.hideLoading({
      noConflict: true,
    });
  }
}

//判断当前用户是否完善信息
const onlyChangeComplete = () => {
  wx.navigateTo({
    url: "/pages/perfectInfo/perfectInfo",
  });
  return;
};

// 判断当前图片是否404
export function checkImg(imgurl) {
  return new Promise(function (resolve, reject) {
    wx.getImageInfo({
      src: imgurl,
      success(res) {
        resolve(res);
      },
      fail(err) {
        reject(err);
      },
    });
  });
}

//提示弹窗
export function popup(confirm, content, cancel, showCancel = true) {
  wx.showModal({
    title: "提示",
    content: content || "是否删除？",
    showCancel: showCancel,
    success(res) {
      if (res.confirm) {
        if (confirm && confirm instanceof Function) {
          confirm();
        } else {
          hint("CallBack is no a function");
        }
      } else if (res.cancel) {
        if (cancel) {
          cancel();
        }
      }
    },
  });
}

// 返回上一页  或  指定页面
export let navBack = (url, delta = 1, time = 1000) => {
  setTimeout(() => {
    if (!url || url == "back")
      return uni.navigateBack({
        delta: delta,
      });

    uni.reLaunch({
      url,
    });
  }, time);
};

// 触发全局的自定义事件 $emit
export let emitTime = (name, data = true, time = 1000) => {
  setTimeout(() => {
    if (name) {
      uni.$emit(name, data);
    }
  }, time);
};

/* 根据条件查找对象 */
export function findItem(arr, params, value) {
  let obj = {};
  if (!(arr instanceof Array)) {
    return;
  }
  obj = arr.find((item) => {
    return item[params] == value;
  });
  return obj;
}

// 预览图片
export function pvwImage(url) {
  return uni.previewImage({
    urls: url,
    success: (res) => {},
  });
}

/* 时间格式化 */
export function formatters(timestamp, type) {
  var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var YY = date.getFullYear();
  var MM =
    date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1;
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var HH = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  var mm = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  var ss = date.getSeconds();
  let time;
  time = YY + "-" + MM + "-" + DD + " " + HH + ":" + mm + ":00";
  if (type == "YY") {
    time = YY;
  }
  if (type == "MM") {
    time = MM;
  }
  if (type == "DD") {
    time = DD;
  }
  if (type == "HH") {
    time = HH;
  }
  if (type == "mm") {
    time = mm;
  }
  if (type == "ss") {
    time = ss;
  }
  if (type == "YY-MM") {
    time = YY + "-" + MM;
  }
  if (type == "YY-MM-DD") {
    time = YY + "-" + MM + "-" + DD;
  }
  if (type == "YY/MM/DD") {
    time = YY + "/" + MM + "/" + DD;
  }
  if (type == "YY-MM-DD HH") {
    time = YY + "-" + MM + "-" + DD + " " + HH;
  }
  if (type == "YY-MM-DD HH:mm") {
    time = YY + "-" + MM + "-" + DD + " " + HH + ":" + mm;
  }
  if (type == "YY/MM/DD HH:mm") {
    time = YY + "/" + MM + "/" + DD + " " + HH + ":" + mm;
  }
  if (type == "YY-MM-DD HH:mm:ss") {
    time = YY + "-" + MM + "-" + DD + " " + HH + ":" + mm + ":" + ss;
  }
  if (type == "timestamp") {
    time = date.getTime();
  }
  if (type == "wordMinute") {
    time = YY + "年" + MM + "月" + DD + "日" + HH + "时" + mm + "分";
  }
  if (type == "wordTime") {
    time = YY + "年" + MM + "月" + DD + "日" + HH + "时";
  }
  if (type == "wordDay") {
    time = YY + "年" + MM + "月" + DD + "日";
  }
  return time;
}

/* 时间格式化 中文*/
export function formattersWord(dateStr) {
  let yymmdd = formatters(dateStr, "YY-MM-DD");

  var dict = {
    0: "零",
    1: "一",
    2: "二",
    3: "三",
    4: "四",
    5: "五",
    6: "六",
    7: "七",
    8: "八",
    9: "九",
    10: "十",
    11: "十一",
    12: "十二",
    13: "十三",
    14: "十四",
    15: "十五",
    16: "十六",
    17: "十七",
    18: "十八",
    19: "十九",
    20: "二十",
    21: "二十一",
    22: "二十二",
    23: "二十三",
    24: "二十四",
    25: "二十五",
    26: "二十六",
    27: "二十七",
    28: "二十八",
    29: "二十九",
    30: "三十",
    31: "三十一",
  };
  var date = yymmdd.split("-"),
    yy = date[0],
    mm = +date[1],
    dd = +date[2];

  var yearStr = dict[yy[0]] + dict[yy[1]] + dict[yy[2]] + dict[yy[3]] + "年",
    monthStr = dict["" + Number(mm)] + "月",
    dayStr = dict[dd] + "日";

  return yearStr + monthStr + dayStr;
}

// 日期转时间戳
export function dayTurnTime(time) {
  var date = new Date(time);
  return date.getTime();
}

/* 筛掉无用得字段 */
export function fitterItem(obj) {
  let params = {};
  if (obj instanceof Object) {
    for (let key in obj) {
      if (obj[key] && obj[key] != "undefined") {
        params[key] = obj[key];
      } else {
        continue;
      }
    }
  }
  return params;
}
export function uploadFile(data) {
  let promise = new Promise((resolve, reject) => {
    uni.uploadFile({
      url: baseURL + data.url,
      ...data,
      success(res) {
        resolve(res);
      },
    });
  });
  return promise;
}

/**
 *  FormData格式传参
 * @param url  上传路径
 * @param name  上传标识名字
 * @param file  文件内容
 * @param data  其他数据
 */
export function uploadFormdata(url, name, file, data = {}) {
  return new Promise((resolve, reject) => {
    let token = uni.getStorageSync("X-MINI-TOKEN");
    wx.request({
      url: baseURL + url,
      method: "POST",
      header: {
        "X-MINI-TOKEN": token,
        "content-type": "application/x-www-form-urlencoded",
      },
      data: json2Form(data),
      success: function (res) {
        console.log(res, "rrrrrrrrrrr");
      },
      fail: function (res) {
        console.log(res, "错误的");
      },
    });
  });
}

export function json2Form(json) {
  var str = [];
  for (var p in json) {
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
  }
  return str.join("&");
}

//身份证校验
export function checkIDCard(idcode) {
  // 函数参数必须是字符串，因为二代身份证号码是十八位，而在javascript中，十八位的数值会超出计算范围，造成不精确的结果，导致最后两位和计算的值不一致，从而该函数出现错误。
  // 加权因子
  var weight_factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  // 校验码
  var check_code = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];

  var code = idcode + "";
  var last = idcode[17]; //最后一位

  var seventeen = code.substring(0, 17);

  // ISO 7064:1983.MOD 11-2
  // 判断最后一位校验码是否正确
  var arr = seventeen.split("");
  var len = arr.length;
  var num = 0;
  for (var i = 0; i < len; i++) {
    num = num + arr[i] * weight_factor[i];
  }

  // 获取余数
  var resisue = num % 11;
  var last_no = check_code[resisue];

  // 格式的正则
  // 正则思路
  /*
      第一位不可能是0
      第二位到第六位可以是0-9
      第七位到第十位是年份，所以七八位为19或者20
      十一位和十二位是月份，这两位是01-12之间的数值
      十三位和十四位是日期，是从01-31之间的数值
      十五，十六，十七都是数字0-9
      十八位可能是数字0-9，也可能是X
      */
  var idcard_patter =
    /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;

  // 判断格式是否正确
  var format = idcard_patter.test(idcode);

  // 返回验证结果，校验码和格式同时正确才算是合法的身份证号码
  return last === last_no && format ? true : false;
}

//*号隐藏信息
export function hiddenInfo(str, frontLen = 3, endLen = 4) {
  var len = str.length - frontLen - endLen;
  var start = "";
  for (var i = 0; i < len; i++) {
    start += "*";
  }
  return (
    str.substring(0, frontLen) + start + str.substring(str.length - endLen)
  );
}

// 图片转为base64
export function getBase64(img) {
  return new Promise((resolve, reject) => {
    wx.downloadFile({
      url: img,
      success(res) {
        wx.getFileSystemManager().readFile({
          filePath: res.tempFilePath, //选择图片返回的相对路径
          encoding: "base64", //编码格式
          success: (res) => {
            resolve("data:image/png;base64," + res.data);
          },
        });
      },
    });
  });
}

// 逾期/倒计时  算出天数
export function getNumberDays(day) {
  let timeStamp = dayTurnTime(day);
  let currentStamp = Date.now();

  if (timeStamp > currentStamp) {
    // 倒计时
    let num_day = Math.ceil((timeStamp - currentStamp) / (1000 * 60 * 60 * 24));
    return [true, num_day];
  } else if (timeStamp < currentStamp) {
    // 逾期
    let num_day = Math.ceil((currentStamp - timeStamp) / (1000 * 60 * 60 * 24));
    return [false, num_day];
  }
}

// 去除空格
export function uniTrim(value, spec = "both") {
  return uni.$u.trim(value);
}

// 正整数
export function isNumber(s) {
  return /^[1-9]\d*$/.test(s);
}

// 只能输入数字，可输入到小数点后两位
export function isNumberTwo(s) {
  return /^(\d+\.?)?\d{0,2}$/.test(s);
}

// 手机号校验
// let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
export function regPhone(s) {
  return /^1(3|4|5|7|8)\d{9}$/.test(s);
}
